#! /usr/bin/python3

import os
import argparse

if __name__ == '__main__':
  parser = argparse.ArgumentParser(
    description="Get address from libso",
    formatter_class=argparse.RawDescriptionHelpFormatter
    )
  parser.add_argument("--dir", type = str,required = True,
    help="profile process with this PID only")
  args = parser.parse_args()

  current_path = os.getcwd()
  flamegraph_path = '{}/FlameGraph-master/flamegraph.pl'.format(current_path)

  g =  os.walk("{}".format(args.dir))

  # split file output folded
  for root, dirs, files in g:

    for file in files:
      search_string1 = ".log"
      search_string2 = ".filt"
      if not search_string1 in file:
        continue

      # if not search_string2 in file:
      #   continue

      if(file.split('.')[1] != 'log'):
        continue

      curpath ="{}/{}".format(root,file)

      intput_file = curpath
      output_file = "{}.filt".format(intput_file)
      excute_cmd = "c++filt < {} > {}".format(intput_file, output_file)
      exit_code = os.system(excute_cmd)
      if exit_code != 0:
        continue

      excute_cmd2 = "rm -rf {}".format(intput_file)
      exit_code = os.system(excute_cmd2)

      f = open(output_file)
      contents = f.read().split('bcc_profile ')


      for content in contents:
        if(len(content) == 0) :
          continue
        time,content = content.split('\n',1)  
        if len(time) < 2:
          continue
        time = time.split(': ')[1]
        out_folded_file = '{}/{}.folded'.format(root,time)
        f = open(out_folded_file, "w")
        f.write(content)
        f.close()

        output_svg_path ="{}/{}".format(root,'output_svg')
        if not os.path.exists(output_svg_path):
          print(output_svg_path)
          os.makedirs(output_svg_path)

        
        excute_cmd3 = '{} < {}  >  {}/{}.svg'.format(flamegraph_path, out_folded_file, output_svg_path, time)
        os.system(excute_cmd3)
       
    excute_cmd4 = "rm -rf {}/*.folded".format(root)
    os.system(excute_cmd4)


        
       